package learn_concurrent._8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T4 {
	static final Logger logger = LoggerFactory.getLogger(T4.class);

	public static void main(String[] args) throws InterruptedException {

		WaitNotify wn = new WaitNotify(1, 5);
		new Thread(() -> wn.print("a", 1, 2), "t1").start();
		new Thread(() -> wn.print("b", 2, 3), "t2").start();
		new Thread(() -> wn.print("c", 3, 1), "t3").start();

	}

}

class WaitNotify {
	private int flag;
	private final int loopNum;
	
	public WaitNotify(int flag, int loopNum) {
		this.flag = flag;
		this.loopNum = loopNum;
	}
	
	public void print(String str, int targetFlag, int nextFlag) {
		for(int i = 0; i < loopNum; i++) {
			synchronized(this) {
				while(flag != targetFlag) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.print(str);
				flag = nextFlag;
				this.notifyAll();
			}
		}
	}
}
